﻿from http.server import BaseHTTPRequestHandler, HTTPServer

class MyHandler(BaseHTTPRequestHandler):

    # 处理 GET 请求
    def do_GET(self):
        if self.path == "/index":
            # HTML 页面内容
            html = """
            <!DOCTYPE html>
            <html lang="zh">
            <head>
                <meta charset="UTF-8">
                <title>服务器端程序示例cp</title>
                <style>
                    body {
                        font-family: "Microsoft YaHei", sans-serif;
                        background-color: #f0f8ff;
                        text-align: center;
                        padding-top: 100px;
                    }
                    h1 {
                        color: #ff69b4;
                        font-size: 48px;
                    }
                    p {
                        color: #555;
                        font-size: 24px;
                    }
                </style>
            </head>
            <body>
                <h1>这是第一行</h1>
                <p>“第一行后分段”</p>
                <p>“再分段”</p>
            </body>
            </html>
            """

            # 设置响应头
            self.send_response(200)
            self.send_header("Content-Type", "text/html; charset=UTF-8")
            self.end_headers()

            # 响应内容
            self.wfile.write(html.encode("utf-8"))

        else:
            # 未知路径 → 返回 404
            self.send_response(404)
            self.send_header("Content-Type", "text/plain; charset=UTF-8")
            self.end_headers()
            self.wfile.write("404 Not Found".encode("utf-8"))


def main():
    host = "127.0.0.1"
    port = 8080

    server = HTTPServer((host, port), MyHandler)
    print(f"请打开您的浏览器，输入：http://{host}:{port}/index")
    print("服务器已启动...")

    server.serve_forever()


if __name__ == "__main__":
    main()
